<script setup lang="ts">
import { prePayAPI, getPatientInfoAPI, createOrderAPI } from '@/services'
import { onMounted, ref } from 'vue'
import type { Patient } from '@/types/user'
import type { PrePayResponse, PartialConsult } from '@/types/consult'
import { useConsultStore } from '@/stores'
import { showConfirmDialog, showDialog, showToast } from 'vant'
import { onBeforeRouteLeave } from 'vue-router'
import router from '@/router'
const store = useConsultStore()

// 定义患者信息数据
const patientInfo = ref<Patient>()
// 定义预支付信息
const previewPayInfo = ref<PrePayResponse>()

onMounted(async () => {
  //判断用户信息字段完整度   keyof 获取类型的键，返回的是一个联合类型形式
  type key = keyof PartialConsult
  const keys: key[] = [
    'type',
    'consultFlag',
    'illnessDesc',
    'illnessTime',
    'illnessType',
    'depId',
    'patientId'
  ]
  // 所有字段的值都不为undefined
  const flag = keys.every((key) => store.consult[key] !== undefined)
  // 如果有一项undefined就表示就诊信息字段不完整
  if (!flag) {
    return showDialog({
      title: '温馨提示',
      message: '支付信息不完整请重新填写',
      closeOnPopstate: false
    }).then(() => {
      router.push('/')
    })
  }
  // 获取患者信息
  if (store.consult.patientId) {
    const res = await getPatientInfoAPI(store.consult.patientId)
    patientInfo.value = res.data
    console.log(patientInfo.value)
  }

  //   获取预支付信息
  const re = await prePayAPI({
    type: store.consult.type,
    illnessType: store.consult.illnessType
  })
  console.log(re.data)

  previewPayInfo.value = re.data

  //   设置优惠券
  store.setCoupon(re.data.couponId)
})

const isAgree = ref(false) //支付协议
const show = ref(false) //抽屉弹层的显示隐藏
const OrderId = ref() //订单ID
const loading = ref(false) //点击支付时的loading效果

// 点击支付
const pay = async () => {
  if (!isAgree.value) return showToast('请阅读支付协议')
  loading.value = true
  // 显示弹层
  show.value = true
  // 调用接口
  const re = await createOrderAPI(store.consult)
  loading.value = false

  // 清空仓库数据
  store.clearStore()
  // 保存订单ID
  OrderId.value = re.data.id
}

// 组件路由钩子函数
onBeforeRouteLeave(() => {
  // 一旦生成订单，就不让回退
  if (OrderId.value) return false
})

// 点击遮罩层触发
const handelClose = () => {
  showConfirmDialog({
    title: '关闭支付',
    message: '取消支付将无法获得医生回复,医生名额有限,是否确认取消',
    confirmButtonText: '继续支付',
    cancelButtonText: '仍要关闭'
  })
    .then(() => {
      return false //啥也不干，不关闭支付弹层,继续进行支付
    })
    .catch(() => {
      // 清空订单ID
      OrderId.value = ''
      // 跳转到问诊记录
      router.push('/user/consult')
      return true //放行
    })
}
</script>

<template>
  <div class="consult-pay-page" v-if="previewPayInfo && patientInfo">
    <cp-nav-bar title="支付" />
    <div class="pay-info">
      <p class="tit">图文问诊 {{ previewPayInfo?.payment }} 元</p>
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <p class="desc">
        <span>极速问诊</span>
        <span>自动分配医生</span>
      </p>
    </div>
    <van-cell-group>
      <van-cell
        title="优惠券"
        :value="`-¥${previewPayInfo?.couponDeduction}`"
      />
      <van-cell
        title="积分抵扣"
        :value="`-¥${previewPayInfo?.pointDeduction}`"
      />
      <van-cell
        title="实付款"
        :value="`-¥${previewPayInfo?.actualPayment}`"
        class="pay-price"
      />
    </van-cell-group>
    <div class="pay-space"></div>
    <van-cell-group>
      <van-cell
        title="患者信息"
        :value="`${patientInfo.name} | ${patientInfo.genderValue} | ${patientInfo.age}岁`"
      ></van-cell>
      <van-cell title="病情描述" :label="store.consult.illnessDesc"></van-cell>
    </van-cell-group>
    <div class="pay-schema">
      <van-checkbox v-model="isAgree"
        >我已同意 <span class="text">支付协议</span></van-checkbox
      >
    </div>
    <van-submit-bar
      :loading="loading"
      button-type="primary"
      :price="previewPayInfo?.actualPayment * 100"
      button-text="立即支付"
      text-align="left"
      @click="pay"
    />
  </div>
  <!-- 骨架屏 -->
  <div class="consult-pay-page" v-else>
    <cp-nav-bar title="支付" />
    <!-- 骨架屏组件 -->
    <van-skeleton title :row="12" />
  </div>
  <!-- 抽屉组件，选择支付方式 -->
  <!-- :close-on-popstate="false"  表示回退时不关闭抽屉组件 -->
  <!-- :closeable="false" 把关闭图标去掉 -->
  <CpPaySheet
    v-if="previewPayInfo && OrderId"
    payCallback="/room"
    v-model:show="show"
    :order-id="OrderId"
    :money="previewPayInfo?.actualPayment"
    :handel-close="handelClose"
  ></CpPaySheet>
  <!-- <van-action-sheet
    :before-close="handelClose"
    :closeable="false"
    v-model:show="show"
    title="选择支付方式"
    :close-on-popstate="false"
  >
    <div class="pay-type">
      <p class="amount">￥20.00</p>
      <van-cell-group>
        <van-cell title="微信支付">
          <template #icon><CpIcons name="consult-wechat" /></template>
          <template #extra
            ><van-checkbox @click="payMethod = 0" :checked="payMethod === 0"
          /></template>
        </van-cell>
        <van-cell title="支付宝支付">
          <template #icon><CpIcons name="consult-alipay" /></template>
          <template #extra
            ><van-checkbox @click="payMethod = 1" :checked="payMethod === 1"
          /></template>
        </van-cell>
      </van-cell-group>
      <div class="btn">
        <van-button type="primary" @click="FastPay" round block
          >立即支付</van-button
        >
      </div>
    </div>
  </van-action-sheet> -->
</template>

<style lang="scss" scoped>
.consult-pay-page {
  padding: 0px 0 50px 0;
}
.pay-info {
  display: flex;
  padding: 15px;
  flex-wrap: wrap;
  align-items: center;
  .tit {
    width: 100%;
    font-size: 16px;
    margin-bottom: 10px;
  }
  .img {
    margin-right: 10px;
    width: 38px;
    height: 38px;
    border-radius: 4px;
    overflow: hidden;
  }
  .desc {
    flex: 1;
    > span {
      display: block;
      color: var(--cp-tag);
      &:first-child {
        font-size: 16px;
        color: var(--cp-text2);
      }
    }
  }
}
.pay-price {
  ::v-deep() {
    .vam-cell__title {
      font-size: 16px;
    }
    .van-cell__value {
      font-size: 16px;
      color: var(--cp-price);
    }
  }
}
.pay-space {
  height: 12px;
  background-color: var(--cp-bg);
}
.pay-schema {
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  .text {
    color: var(--cp-primary);
  }
}
::v-deep() {
  .van-submit-bar__button {
    font-weight: normal;
    width: 160px;
  }
}
.pay-type {
  .amount {
    padding: 20px;
    text-align: center;
    font-size: 16px;
    font-weight: bold;
  }
  .btn {
    padding: 15px;
  }
  .van-cell {
    align-items: center;
    .cp-icon {
      margin-right: 10px;
      font-size: 18px;
    }
    .van-checkbox :deep(.van-checkbox__icon) {
      font-size: 16px;
    }
  }
}
</style>
